//
//  ParticleSystemCacheUtil.cpp
//  firebkball
//
//  Created by ren jian on 18/6/4.
//
//

#include "ParticleSystemCacheUtil.h"

#include "ParticleSystemCacheUtil.h"

ParticleSystemCacheUtil*  ParticleSystemCacheUtil::_self = NULL;

ParticleSystemCacheUtil* ParticleSystemCacheUtil::getSingleInstance(){
    if (!_self) {
        _self = new ParticleSystemCacheUtil();
        _self->autorelease();
        _self->retain();
    }
    return _self;
}

ParticleSystemCacheUtil::~ParticleSystemCacheUtil(){
    CC_SAFE_RELEASE_NULL(cache);
    CC_SAFE_RELEASE_NULL(_self);
}

ParticleSystemCacheUtil::ParticleSystemCacheUtil(){
    cache = Dictionary::create();
    cache->retain();
}

ParticleSystemQuad* ParticleSystemCacheUtil::addOrGetParticleSystem(const char *plistFile){
    Dictionary *dict = ( Dictionary *)cache->objectForKey(plistFile);
    if (!dict) {
        dict = Dictionary::createWithContentsOfFileThreadSafe(plistFile);
        cache->setObject(dict, plistFile);
    }else{
        //        CCLOG("使用缓存的粒子文件");
    }
    return ParticleSystemQuad_AHA::create(plistFile);
}

void ParticleSystemCacheUtil::clearCache(){
    if (cache) {
        cache->removeAllObjects();
    }
    CC_SAFE_RELEASE_NULL(cache);
    CC_SAFE_RELEASE_NULL(_self);
}


//TODO:粒子实现
ParticleSystemQuad_AHA* ParticleSystemQuad_AHA::createWithDic(Dictionary *data,const char *plistFile){
    ParticleSystemQuad_AHA *obj = new ParticleSystemQuad_AHA();
    if (obj && obj->initWithFileData(data,plistFile)) {
        obj->autorelease();
    }else{
        CC_SAFE_DELETE(obj);
        obj = NULL;
    }
    return  obj;
}

bool ParticleSystemQuad_AHA::initWithFileData(Dictionary *data,const char *plistFile)
{
    bool bRet = false;
    std::string  pf = FileUtils::getInstance()->fullPathForFilename(plistFile);
    Dictionary *dict=NULL;
    if (!data) {
        dict = CCDictionary::createWithContentsOfFileThreadSafe(pf.c_str());
    }else{
        dict=data;
    }
    
    CCAssert( dict != NULL, "Particles: file not found");
    
    // XXX compute path from a path, should define a function somewhere to do it
    std::string listFilePath = plistFile;
    if (listFilePath.find('/') != std::string::npos)
    {
        listFilePath = listFilePath.substr(0, listFilePath.rfind('/') + 1);
        bRet = this->initWithFileData(dict, listFilePath.c_str());
        //        bRet = this->initWithDictionary(dict, listFilePath.c_str());
    }
    else
    {
        //        bRet = this->initWithDictionary(dict, "");
        bRet = this->initWithFileData(dict,"");
    }
    
    dict->release();
    
    return bRet;
}